import axios, { InternalAxiosRequestConfig, AxiosResponse, AxiosRequestConfig } from 'axios'
import {notification, message} from 'antd'
import { getSession } from '@bastet/utils'
import ErrorCode from './error-code'

function createParams(params: any) {
  var string = ''
  // 如果是 字符串
  if(typeof params === 'object') {
    // 如果是 对象
    for(var i in params) {
      string += ( '&' + i + '=' + encodeURIComponent(params[i]))
    }
  }
  return string
}

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
const DURATION = 5000;
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  // baseURL: 'http://localhost:4003/api/',
  baseURL: '/api/',
  // 超时
  timeout: 60000
})

// request拦截器
service.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  config.headers['Authorization'] = 'Bearer ' + getSession('token'); // 让每个请求携带自定义token 请根据实际情况自行修改
  return config
}, (error: any) => {
  console.log(error)
  return Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use((res: AxiosResponse) => {
  /*
     未设置状态码则默认成功状态
    */
  let code = res.data?.code
  // @ts-ignore 获取错误信息
  const msg = ErrorCode[`error:${code}`] || res.data.msg || ErrorCode['error:default']
  if (code === 401) {
    notification.warning({
        message: '重新登录',
        description: '登录状态已过期，您可以继续留在该页面，或者重新登录',
        duration: DURATION,
        onClick: () => {

        }
    }
    )/*.then(() => {
      /!*store.dispatch('user/$$LogOut').then(() => {
        location.href = '/index'
      })*!/
    })*/
  } else if (code === 500) {
    message.error(msg, DURATION)
    return Promise.reject(new Error(msg))
  } else if (code !== 200) {
    notification.error({
      message: msg,
      duration: DURATION
    })
    // eslint-disable-next-line prefer-promise-reject-errors
    return Promise.reject(res.data)
  } else {
    return res.data
  }
}, (error: { message: string; length: number }) => {
  console.log('err' + error)
  if (error.message === 'Network Error') {
    message.error('后端接口连接异常', DURATION)
  } else if (error.message.includes('timeout')) {
    message.error('系统接口请求超时', DURATION)
  } else if (error.message.includes('Request failed with status code')) {
    message.error('系统接口' + error.message.substr(error.message.length - 3) + '异常', DURATION)
  }

  return Promise.reject(error)
})

export default {
  get(url: string, params?: any, config?: AxiosRequestConfig) {
    if (params) url += '?' + createParams(params)
    return service.get(url, config).catch(error => error)
  },
  post(url: string, data: any, config?: AxiosRequestConfig) {
    return service.post(url, data, config).catch(error => error)
  },
  put(url: string, data: any, config?: AxiosRequestConfig) {
    return service.put(url, data, config).catch(error => error)
  },
  delete(url: string, config?: AxiosRequestConfig) {
    return service.delete(url, config).catch(error => error)
  },
}
